<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="文章来源： 用 Rust 构建你自己的 JavaScript 运行时(中文) 用 Rust 构建你自己的 JavaScript 运行时(原文) 下面是笔者在自己机器上实践的过程，讲解一些原文中没提到的坑，建议先过一遍上面提到的文章再跟着这个实践。">
<meta property="og:type" content="article">
<meta property="og:title" content="用 Rust 构建你自己的 JavaScript 运行时实践（1）">
<meta property="og:url" content="https://wyatex.online/Rust/rust-build-js-runtime-1/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="文章来源： 用 Rust 构建你自己的 JavaScript 运行时(中文) 用 Rust 构建你自己的 JavaScript 运行时(原文) 下面是笔者在自己机器上实践的过程，讲解一些原文中没提到的坑，建议先过一遍上面提到的文章再跟着这个实践。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4ae9903e39aa47b5bb5a8c9c599bc8c1~tplv-k3u1fbpfcp-watermark.image">
<meta property="og:image" content="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/27e97e34d71a4946a31aa88b28997e0c~tplv-k3u1fbpfcp-watermark.image">
<meta property="article:published_time" content="2023-09-15T09:54:59.000Z">
<meta property="article:modified_time" content="2023-09-15T09:58:47.169Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="rust">
<meta property="article:tag" content="deno">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4ae9903e39aa47b5bb5a8c9c599bc8c1~tplv-k3u1fbpfcp-watermark.image">


<link rel="canonical" href="https://wyatex.online/Rust/rust-build-js-runtime-1/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/Rust/rust-build-js-runtime-1/","path":"Rust/rust-build-js-runtime-1/","title":"用 Rust 构建你自己的 JavaScript 运行时实践（1）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>用 Rust 构建你自己的 JavaScript 运行时实践（1） | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%B5%B7%E6%AD%A5"><span class="nav-number">1.</span> <span class="nav-text">起步</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%86%E5%A4%87%E7%8E%AF%E5%A2%83"><span class="nav-number">1.1.</span> <span class="nav-text">准备环境</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE"><span class="nav-number">1.2.</span> <span class="nav-text">创建项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Hello-runjs"><span class="nav-number">1.3.</span> <span class="nav-text">Hello, runjs!</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%89%8B%E5%8A%A8%E4%B8%8B%E8%BD%BDv8%E4%BE%9D%E8%B5%96"><span class="nav-number">1.4.</span> <span class="nav-text">手动下载v8依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B7%BB%E5%8A%A0%E4%B8%80%E4%BA%9BApi"><span class="nav-number">1.5.</span> <span class="nav-text">添加一些Api</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Rust/rust-build-js-runtime-2/" rel="bookmark">
        <time class="popular-posts-time">2023-09-15</time>
        <br>
      用 Rust 构建你自己的 JavaScript 运行时实践（2）
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/Rust/rust-build-js-runtime-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="用 Rust 构建你自己的 JavaScript 运行时实践（1） | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          用 Rust 构建你自己的 JavaScript 运行时实践（1）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2023-09-15 17:54:59 / 修改时间：17:58:47" itemprop="dateCreated datePublished" datetime="2023-09-15T17:54:59+08:00">2023-09-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Rust/" itemprop="url" rel="index"><span itemprop="name">Rust</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><blockquote>
<p>文章来源：</p>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7262693723493662777">用 Rust 构建你自己的 JavaScript 运行时(中文)</a></p>
<p><a target="_blank" rel="noopener" href="https://deno.com/blog/roll-your-own-javascript-runtime">用 Rust 构建你自己的 JavaScript 运行时(原文)</a></p>
<p>下面是笔者在自己机器上实践的过程，讲解一些原文中没提到的坑，建议先过一遍上面提到的文章再跟着这个实践。</p>
</blockquote>
<span id="more"></span>

<h1 id="起步"><a href="#起步" class="headerlink" title="起步"></a>起步</h1><h2 id="准备环境"><a href="#准备环境" class="headerlink" title="准备环境"></a>准备环境</h2><p>原文不清楚是使用什么环境，笔者使用的是Windows11系统，整体实践下来会有点出入。我的rustup和rustc版本：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ rustup -V</span><br><span class="line">rustup 1.26.0 (5af9b9484 2023-04-05)</span><br><span class="line">info: This is the version for the rustup toolchain manager, not the rustc compiler.</span><br><span class="line">info: The currently active `rustc` version is `rustc 1.71.1 (eb26296b5 2023-08-03)`</span><br></pre></td></tr></table></figure>

<p>如果没安装rustup的话可以按照rustup官方文档安装即可，笔者使用了winget进行安装。</p>
<p>编译器后端需要选择msvc，所以toolchain要选择msvc，不能选择gnu，后面介绍为什么只能选msvc</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ rustup toolchain list</span><br><span class="line">stable-x86_64-pc-windows-gnu</span><br><span class="line">stable-x86_64-pc-windows-msvc (default)</span><br><span class="line">1.60.0-x86_64-pc-windows-msvc</span><br><span class="line"></span><br><span class="line"># 如果你当前是gnu的toolchain，可以这样设置成msvc是默认toolchain</span><br><span class="line">$ rustup default stable-x86_64-pc-windows-msvc</span><br></pre></td></tr></table></figure>

<p>既然用到msvc作为编译器后端，那么肯定要装msvc了，笔者使用的是vscode2022，这是我安装的c&#x2F;c++编译组件</p>
<p><img data-src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4ae9903e39aa47b5bb5a8c9c599bc8c1~tplv-k3u1fbpfcp-watermark.image" alt="微信截图_20230808171315.png"></p>
<p>其中必须的组件是：C++的桌面开发中的MSVC v143… 、Windows 11 SDK…</p>
<p>如果是旧版本或者新版本的vs可能会显示不一样的版本号，但是应该都是差不多的而且能跑的（有用vs进行windows桌面开发的大佬可以解答一下）。</p>
<p>除此之外，建议配置一下cargo镜像源，请看：<a target="_blank" rel="noopener" href="https://rsproxy.cn/">rsproxy</a>，当然也可以选择ustc的镜像。</p>
<p>而且，建议准备一个加速器，下面的实践过程需要访问github下载v8，最好准备一个，以防万一。</p>
<h2 id="创建项目"><a href="#创建项目" class="headerlink" title="创建项目"></a>创建项目</h2><p>找个你喜欢的目录，新建个项目：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">$ cargo init --bin runjs</span><br><span class="line">     Created binary (application) package</span><br><span class="line">     </span><br><span class="line"># 添加deno和tokio依赖，建议使用@指定版本，不然最新的版本可能api不一样，用下面的代码会因为参数不一致无法通过编译</span><br><span class="line">$ cd runjs</span><br><span class="line"></span><br><span class="line">$ cargo add deno_core@0.174.0</span><br><span class="line">    Updating `ustc` index</span><br><span class="line">      Adding deno_core v0.174.0 to dependencies.</span><br><span class="line">             Features:</span><br><span class="line">             + v8_use_custom_libcxx</span><br><span class="line">             - include_js_files_for_snapshotting</span><br><span class="line">    Updating `ustc` index</span><br><span class="line">$ cargo add tokio@1.25.0 --features=full</span><br><span class="line">.......</span><br></pre></td></tr></table></figure>

<h2 id="Hello-runjs"><a href="#Hello-runjs" class="headerlink" title="Hello, runjs!"></a>Hello, runjs!</h2><p>修改main.rs</p>
<figure class="highlight rust"><figcaption><span>main.rs</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// main.rs</span></span><br><span class="line"><span class="keyword">use</span> std::rc::Rc;</span><br><span class="line"><span class="keyword">use</span> deno_core::error::AnyError;</span><br><span class="line"></span><br><span class="line"><span class="keyword">async</span> <span class="keyword">fn</span> <span class="title function_">run_js</span>(file_path: &amp;<span class="type">str</span>) <span class="punctuation">-&gt;</span> <span class="type">Result</span>&lt;(), AnyError&gt; &#123;</span><br><span class="line">  <span class="keyword">let</span> <span class="variable">main_module</span> = deno_core::<span class="title function_ invoke__">resolve_path</span>(file_path)?;</span><br><span class="line">  <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">js_runtime</span> = deno_core::JsRuntime::<span class="title function_ invoke__">new</span>(deno_core::RuntimeOptions &#123;</span><br><span class="line">      module_loader: <span class="title function_ invoke__">Some</span>(Rc::<span class="title function_ invoke__">new</span>(deno_core::FsModuleLoader)),</span><br><span class="line">      ..<span class="built_in">Default</span>::<span class="title function_ invoke__">default</span>()</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> <span class="variable">mod_id</span> = js_runtime.<span class="title function_ invoke__">load_main_module</span>(&amp;main_module, <span class="literal">None</span>).<span class="keyword">await</span>?;</span><br><span class="line">  <span class="keyword">let</span> <span class="variable">result</span> = js_runtime.<span class="title function_ invoke__">mod_evaluate</span>(mod_id);</span><br><span class="line">  js_runtime.<span class="title function_ invoke__">run_event_loop</span>(<span class="literal">false</span>).<span class="keyword">await</span>?;</span><br><span class="line">  result.<span class="keyword">await</span>?</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">  <span class="keyword">let</span> <span class="variable">runtime</span> = tokio::runtime::Builder::<span class="title function_ invoke__">new_current_thread</span>()</span><br><span class="line">    .<span class="title function_ invoke__">enable_all</span>()</span><br><span class="line">    .<span class="title function_ invoke__">build</span>()</span><br><span class="line">    .<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line">  <span class="keyword">if</span> <span class="keyword">let</span> <span class="variable">Err</span>(error) = runtime.<span class="title function_ invoke__">block_on</span>(<span class="title function_ invoke__">run_js</span>(<span class="string">&quot;./example.js&quot;</span>)) &#123;</span><br><span class="line">    <span class="built_in">eprintln!</span>(<span class="string">&quot;error: &#123;&#125;&quot;</span>, error);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在项目根目录添加example.js，注意不是src下是项目根目录：</p>
<figure class="highlight js"><figcaption><span>example.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// example.js</span></span><br><span class="line"><span class="title class_">Deno</span>.<span class="property">core</span>.<span class="title function_">print</span>(<span class="string">&quot;Hello runjs!&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>然后运行一下，如果是正常的话会成功打印：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ cargo run</span><br><span class="line">.....</span><br><span class="line">Hello runjs!</span><br></pre></td></tr></table></figure>

<h2 id="手动下载v8依赖"><a href="#手动下载v8依赖" class="headerlink" title="手动下载v8依赖"></a>手动下载v8依赖</h2><p>但是我相信很多在大陆的小伙伴都不会一步成功，当然如果是成功打印Hello runjs，可以跳过下面这步。<br>这时候控制台会提示下载<code>rusty_v8_release_x86_64-pc-windows-msvc.lib</code>失败，这是一个github的资源，这时候就需要用到你的魔法了，复制链接到浏览器进行下载，或者去github找到对应版本的v8，进行下载。</p>
<p><img data-src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/27e97e34d71a4946a31aa88b28997e0c~tplv-k3u1fbpfcp-watermark.image" alt="微信截图_20230809162743.png"></p>
<p>可以看到windows系统下只有msvc的包，前面如果你使用gnu-toolchain和mingw进行编译则会报错。</p>
<p>找一个地方存放这个lib文件，比如笔者打算放到：<code>D:\rusty_v8</code>，那么在这个文件夹下创建一个目录：<code>v0.XX.X</code>，比如如果你上面是按照我的命令来的话，应该是<code>v0.64.0</code>版本，然后把lib文件丢进去，<br>这时候的文件路径就是：<code>D:\rusty_v8\v0.64.0\rusty_v8_release_x86_64-pc-windows-msvc.lib</code>。</p>
<p>然后前往系统环境变量设置界面，设置环境变量：<code>RUSTY_V8_MIRROR</code>，值是：<code>D:\rusty_v8</code></p>
<p>这样再执行一次 <code>cargo run</code> 应该就能看到正常打印了。</p>
<h2 id="添加一些Api"><a href="#添加一些Api" class="headerlink" title="添加一些Api"></a>添加一些Api</h2><p>在src目录下创建<code>runtime.js</code>：</p>
<figure class="highlight js"><figcaption><span>src/runtime.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// runtime.js</span></span><br><span class="line">(<span class="function">(<span class="params">globalThis</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> core = <span class="title class_">Deno</span>.<span class="property">core</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">function</span> <span class="title function_">argsToMessage</span>(<span class="params">...args</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> args.<span class="title function_">map</span>(<span class="function">(<span class="params">arg</span>) =&gt;</span> <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(arg)).<span class="title function_">join</span>(<span class="string">&quot; &quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    globalThis.<span class="property">console</span> = &#123;</span><br><span class="line">        <span class="attr">log</span>: <span class="function">(<span class="params">...args</span>) =&gt;</span> &#123;</span><br><span class="line">            core.<span class="title function_">print</span>(<span class="string">`[out]: <span class="subst">$&#123;argsToMessage(...args)&#125;</span>\n`</span>, <span class="literal">false</span>);</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">error</span>: <span class="function">(<span class="params">...args</span>) =&gt;</span> &#123;</span><br><span class="line">            core.<span class="title function_">print</span>(<span class="string">`[err]: <span class="subst">$&#123;argsToMessage(...args)&#125;</span>\n`</span>, <span class="literal">true</span>);</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;)(globalThis);</span><br></pre></td></tr></table></figure>

<p>现在只是简单的封装了一下print，下一章实践实现文件系统的读写和删除文件、fetch，第三章实践添加ts转移模块，实现ts直接转js运行（如果内容不多可能合在一起写）。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/Rust/rust-build-js-runtime-1/" title="用 Rust 构建你自己的 JavaScript 运行时实践（1）">https://wyatex.online/Rust/rust-build-js-runtime-1/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/rust/" rel="tag"># rust</a>
              <a href="/tags/deno/" rel="tag"># deno</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/TypeScript/%E4%B8%BA%E4%BB%80%E4%B9%88Object-keys%E4%B8%8D%E8%83%BD%E6%AD%A3%E7%A1%AE%E5%9C%B0%E7%B1%BB%E5%9E%8B%E6%8E%A8%E5%AF%BC/" rel="prev" title="为什么Object.keys不能正确地类型推导">
                  <i class="fa fa-angle-left"></i> 为什么Object.keys不能正确地类型推导
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/Rust/rust-build-js-runtime-2/" rel="next" title="用 Rust 构建你自己的 JavaScript 运行时实践（2）">
                  用 Rust 构建你自己的 JavaScript 运行时实践（2） <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
